<template>
  <Dialog title="费用明细" v-model="dialogVisible">
   <div class="flex flex-items-center" style="margin-bottom: 10px;">
    <span>分摊规则:</span>
       <el-radio-group v-model="allocationRules">
      <el-radio value="1" size="large" >金额</el-radio>
      <el-radio value="2" size="large">数量</el-radio>
    </el-radio-group>
  </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
      label-width="0px"
      :inline-message="true"
      :disabled="disabled"
    >
  
      <el-table
        border
        :data="formData"
        show-summary
        :summary-method="getSummaries"
        class="-mt-10px"
      >
        <el-table-column label="序号" type="index" align="center" width="60" />
        <el-table-column label="供应商" min-width="125">
          <template #default="{ row, $index }">
            <el-form-item :prop="`${$index}.vendor`" :rules="formRules.vendor" class="mb-0px!">
              <el-select
                v-model="row.vendor"
                clearable
                filterable
                placeholder="请选择"
                @change="onChangeWarehouse($event, row)"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="支出类型" min-width="180">
          <template #default="{ row, $index }">
            <el-form-item
              :prop="`${$index}.expenseType`"
              :rules="formRules.expenseType"
              class="mb-0px!"
            >
              <el-select
                v-model="row.expenseType"
                clearable
                filterable
                @change="onChangeProduct($event, row)"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in expenseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="不含税金额" prop="beforeTax" fixed="right" min-width="140">
          <template #default="{ row, $index }">
            <el-form-item
              :prop="`${$index}.beforeTax`"
              :rules="formRules.beforeTax"
              class="mb-0px!"
            >
              <el-input-number
                v-model="row.beforeTax"
                controls-position="right"
                :min="0.00"
                :precision="3"
                class="!w-100%"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="税率(%)" prop="rate" min-width="140">
          <template #default="{ row, $index }">
            <el-form-item :prop="`${$index}.rate`" :rules="formRules.rate" class="mb-0px!">
              <el-input-number
                v-model="row.rate"
                controls-position="right"
                :min="0.00"
                :precision="3"
                class="!w-100%"
              />
            </el-form-item>
          </template>
        </el-table-column>
       <el-table-column label="含税金额" prop="tax" fixed="right" min-width="140">
  <template #default="{ row }">
    <!-- 移除v-model绑定，改用计算属性 -->
    <el-input-number
      :model-value="row.tax"
      @update:modelValue="handleTaxUpdate($event, row)"
      controls-position="right"
      :min="0.00"
      :precision="3"
      class="!w-100%"
    />
  </template>
</el-table-column>
        <el-table-column label="备注" min-width="150">
          <template #default="{ row, $index }">
            <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
              <el-input maxlength="10" v-model="row.remark" placeholder="请输入" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="60">
          <template #default="{ $index }">
            <el-button @click="handleDelete($index)" link>—</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <el-row justify="center" class="mt-3" v-if="!disabled">
      <el-button @click="handleAdd" round>+ 添加费用明细</el-button>
    </el-row>
  </Dialog>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { StockApi } from '@/api/erp/stock/stock'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'
const dialogVisible = ref(false) // 弹窗的是否展示
const props = defineProps<{
  items: undefined
  disabled: false
}>()
const allocationRules = ref('1')
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  vendor: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
  expenseType: [{ required: true, message: '支出类型不能为空', trigger: 'blur' }],
  beforeTax: [{ required: true, message: '不含税金额不能为空', trigger: 'blur' }],
  rate: [{ required: true, message: '税率不能为空', trigger: 'blur' }],
  tax: [{ required: true, message: '含税金额不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const defaultWarehouse = ref<WarehouseVO>(undefined) // 默认仓库

/** 初始化设置入库项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val
  },
  { immediate: true }
)

/** 监听合同产品变化，计算合同产品总价 */
// watch(
//   () => formData.value,
//   (val) => {
//     if (!val || val.length === 0) {
//       return
//     }
//     // 循环处理
//     val.forEach((item) => {
//       item.totalPrice = erpPriceMultiply(item.beforeTax, item.tax)
//     })
//   },
//   { deep: true }
// )

/** 合计 */
const handleTaxUpdate = (value: number, row: any) => {
  row.tax = value
  row.beforeTax = value / (1 + row.rate/100)
}

// 优化合计方法
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  const beforeTaxTotal = data.reduce((sum, item) => sum + Number(item.beforeTax || 0), 0)
  const taxTotal = data.reduce((sum, item) => sum + Number(item.tax || 0), 0)

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    switch (column.property) {
      case 'beforeTax':
        sums[index] = erpPriceInputFormatter(beforeTaxTotal)
        break
      case 'tax':
        sums[index] = erpPriceInputFormatter(taxTotal)
        break
      default:
        sums[index] = ''
    }
  })
  return sums
}
/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    warehouseId: defaultWarehouse.value?.id,
    productId: undefined,
    productUnitName: undefined, // 产品单位
    productBarCode: undefined, // 产品条码
    productPrice: undefined,
    stockCount: undefined,
    count: 1,
    totalPrice: undefined,
    remark: undefined
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 处理仓库变更 */
const onChangeWarehouse = (warehouseId, row) => {
  // 加载库存
  setStockCount(row)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productUnitName = product.unitName
    row.productBarCode = product.barCode
    row.productPrice = product.minPrice
  }
  // 加载库存
  setStockCount(row)
}

/** 加载库存 */
const setStockCount = async (row) => {
  if (!row.productId || !row.warehouseId) {
    return
  }
  const stock = await StockApi.getStock2(row.productId, row.warehouseId)
  row.stockCount = stock ? stock.count : 0
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
const open = async () => {
  dialogVisible.value = true
}
defineExpose({ validate, open })

/** 初始化 */
onMounted(async () => {
  productList.value = await ProductApi.getProductSimpleList()
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  defaultWarehouse.value = warehouseList.value.find((item) => item.defaultStatus)
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})
</script>
